'use strict';
import React, {Component} from "react";
import {
    View,
    Text,
    Image,
    TouchableOpacity,
    StyleSheet,
    Dimensions,
    NativeModules,
    Linking,
    Platform,
    ActivityIndicator,
    InteractionManager
} from "react-native";
import ParallaxScrollView from "react-native-parallax-scroll-view";
import FixedHeader from "../Components/FixedHeader";
import WatchMapView from "../Components/WatchMapView";
import {_renderStar, _renderStickyHeader} from "../Utils/ViewUtils";
import LiveData from "../data/LiveData";
import ViewPager from "react-native-viewpager";
import ImageViewer from "../Pages/ImageViewer";
import BottomShareView from "../Components/BottomShareView";
import AllCommentPage from "../Pages/AllCommentPage";
import SomethingItemView from "../Components/SomethingItemView";
import RuralLibraryAPIService from "../Commom/RuralLibraryAPIService";
import Global from "../Commom/GlobalConst";
import ReviewsContainer from "../Containers/ReviewsContainer";
import Toast from "../Utils/toast";
let width = Dimensions.get('window').width;
import RegisteredContainer from '../Containers/RegisteredContainer';
import WebContainer from "../Components/WebContainer";
const styles = StyleSheet.create({
    star: {
        width: 20,
        height: 20,
        marginRight: 5
    },
    borderStyles: {
        borderTopWidth: 10,
        borderColor: '#F2F3F5',
    },
    somethingStyle: {
        flexDirection: 'row',
        padding: 15,
        paddingBottom: 5,
        alignItems: 'center',
    },
    rowContent: {
        flexDirection: 'row',

    },
    imageBox: {
        marginTop: 7,
        width: (width - 60) / 4,
        height: (width - 60) / 4,
    },
    content: {
        backgroundColor: 'white',
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        height: 45,
    },
    textBox: {
        fontSize: 12,
        color: 'red'
    },
    roomItemBox: {
        padding: 15,
        borderBottomWidth: 1,
        borderBottomColor: '#F2F3F5',
    },
    roomTitleBox: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    dimGrayText: {fontSize: 14, color: '#333'},
    lightGrayText: {fontSize: 13, color: '#999'},
    redText: {color: 'red', fontSize: 15, marginRight: 3},
    icon10: {width: 10, height: 10, resizeMode: 'contain', marginLeft: 3},
});
/**
 * 住宿详情
 */
class StayDetailsPage extends Component {

    constructor(props) {
        super(props);
        this.state = {
            flag: false,
            introduce: {},
            commentList: [],
            roomList: [],
            hotelList: [],
            dataSource: new ViewPager.DataSource({
                pageHasChanged: (p1, p2) => p1 !== p2,
            }),
            images: [],
            showImage: [],
            is_collect: 0,
        }
    }

    componentDidMount() {
        let id = this.props.ID;
        if (!id) {
            id = 1;
        }
        InteractionManager.runAfterInteractions(() => {
            RuralLibraryAPIService.hotelDetails(Global.Const.token, Global.Const.registeredId, id).then((ret)=> {
                let data = LiveData.LiveDetails[id - 1];
                let introduce = {
                    id: ret.id,
                    title: ret.rural_title,
                    star: ret.star,
                    desc: ret.content,
                    address: ret.address,
                    phone: ret.mobile,
                    price: ret.price,
                    latitude: ret.latitude,
                    longitude: ret.longitude,
                };
                this.setState({
                    introduce,
                    images: ret.images,
                    commentList: ret.comment_list,
                    roomList: ret.room_list,
                    hotelList: ret.hotel_list,
                    dataSource: this.state.dataSource.cloneWithPages(ret.images),
                    flag: true,
                    is_collect: ret.is_collect,
                })
            }).catch((err)=> {

            });
        });
    }

    refreshComments() {
        let id = this.props.ID;
        if (!id) {
            id = 1;
        }
        RuralLibraryAPIService.hotelDetails(Global.Const.token, Global.Const.registeredId, id).then((ret)=> {
            this.setState({
                commentList: ret.comment_list,
            })
        }).catch((err)=> {

        });
    }

    goToImageViewer() {
        this.props.navigator.push({
            name: 'ImageViewer',
            component: ImageViewer,
            passProps: {
                source: this.state.images,
            }
        })
    }

    goToHotelImageViewer(images) {
        this.props.navigator.push({
            name: 'ImageViewer',
            component: ImageViewer,
            passProps: {
                source: images,
            }
        })
    }

    ReviewsContainer(id, type) {
        if (Global.Const.token == '') {
            // Toast.show('请先登录！');
            this.props.navigator.push({
                id: 'RegisteredContainer',
                component: RegisteredContainer,
                passProps: {},
            });
            return;
        }
        this.props.navigator.push({
            name: 'ReviewsContainer',
            component: ReviewsContainer,
            passProps: {
                rid: id,
                type: type,
                refreshComments: ()=>this.refreshComments(),
            },
        })

    }

    collect() {
        if (Global.Const.token == '') {
            // Toast.show('请先登录！');
            this.props.navigator.push({
                id: 'RegisteredContainer',
                component: RegisteredContainer,
                passProps: {},
            });
            return;
        }
        RuralLibraryAPIService.hotel_collection(Global.Const.token, Global.Const.registeredId, this.props.ID).then((ret)=> {
            if (this.state.is_collect == '0') {
                this.setState({
                    is_collect: '1',
                });
            } else {
                this.setState({
                    is_collect: '0',
                });
            }
        }).catch((err)=> {

        });
    }

    _renderRoomView() {
        return (
            <View style={{
                borderTopColor: '#F2F3F5',
                borderTopWidth: 10,
            }}>
                {
                    this.state.roomList ?
                        this.state.roomList.map((item, index) => {
                            let images = item.images;
                            return (
                                <TouchableOpacity
                                    key={"roomItem" + index}
                                    onPress={()=> {
                                        let showImage = this.state.showImage;
                                        showImage[index] = !showImage[index];
                                        this.setState({
                                            showImage
                                        })
                                    }}
                                >
                                    <View style={styles.roomItemBox}>
                                        <View style={styles.roomTitleBox}>
                                            <View style={{flex: 1, justifyContent: 'center'}}>
                                                <Text style={styles.dimGrayText}>{item.title}</Text>
                                                <Text style={styles.lightGrayText}>{item.content}</Text>
                                            </View>
                                            <View style={styles.roomTitleBox}>
                                                <Text style={styles.lightGrayText}>
                                                    <Text style={styles.redText}>￥{item.price}</Text>
                                                    起
                                                </Text>
                                                <Image style={styles.icon10}
                                                       source={!this.state.showImage[0] ?
                                                           require("../../Image/icon_gray_down.png") :
                                                           require('../../Image/icon_gray_up.png')}
                                                />
                                            </View>
                                        </View>
                                        <View style={styles.rowContent}>
                                            {
                                                item.images && this.state.showImage[index] ?
                                                    item.images.map((item, index)=> {
                                                        let marginRight = ((index + 1) % 4 === 0) ? 0 : 7;
                                                        if (index === 4) {
                                                            return;
                                                        }
                                                        return (
                                                            <TouchableOpacity
                                                                key={'img' + index}
                                                                onPress={() => this.goToHotelImageViewer(images)}
                                                            >
                                                                <Image
                                                                    style={[styles.imageBox, {marginRight}]}
                                                                    source={{uri:item}}
                                                                />
                                                            </TouchableOpacity>
                                                        )
                                                    }) : null
                                            }
                                        </View>
                                    </View>
                                </TouchableOpacity>
                            )
                        }) : null
                }
            </View>
        )
    }

    _renderViewPager() {
        return (
            <View style={{height: 245,width}}>
                {this.state.images.length > 1
                    ?
                    <ViewPager
                        locked={false}
                        isLoop={true}
                        autoPlay={true}
                        renderPageIndicator={false}
                        renderPage={(page) => {
                    return (
                        <TouchableOpacity onPress={() => this.goToImageViewer(page)}>
                            <Image source={{uri:page}}style={{height: 245,width,}}
                            />
                        </TouchableOpacity>
                    )
                }}
                        dataSource={this.state.dataSource}
                    />
                    :
                    <TouchableOpacity onPress={() => this.goToImageViewer()}>
                        <Image source={{uri:this.state.images[0]}} style={{height: 245,width}}
                        />
                    </TouchableOpacity>}
                <View style={{
                    position: 'absolute',
                    backgroundColor: 'rgba(0,0,0,0.3)',
                    width,
                    padding: 10,
                    left: 0,
                    bottom: 0,
                    right: 0,
                    flexDirection: 'row',
                    alignItems: 'center',
                }}>
                    <Text style={{
                        color: 'white',
                        fontSize: 20,
                        flex: 1
                    }}>{this.state.introduce.title}</Text>
                    <Text style={{
                        color: 'white',
                        fontSize: 12,
                    }}>{this.state.dataSource.getPageCount()}张</Text>
                </View>
            </View>
        )
    }

    render() {
        var html = '<!DOCTYPE html><html lang="zh-cn"><head><meta charset="utf8" /><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=0"></head><body><div style="padding: 8px;">' + this.state.introduce.desc + '</div></body></html>';

        let collectImg = this.state.is_collect == '1' ?
            require('../../Image/collect_icon.png')
            : require('../../Image/un_collect_icon.png');
        return (
            <View style={{flex: 1,}}>
                {
                    this.state.flag ?
                        <ParallaxScrollView
                            showsVerticalScrollIndicator={false}
                            contentBackgroundColor={'white'}
                            backgroundColor={'white'}
                            headerBackgroundColor="#333"
                            stickyHeaderHeight={ 65 }
                            parallaxHeaderHeight={ 245 }
                            backgroundSpeed={10}
                            renderForeground={() => this._renderViewPager()}
                            renderFixedHeader={()=> {
                                return (
                                    <FixedHeader rightFunc={()=> {
                                        this.shareView && this.shareView.showShareView();
                                    }} navigator={this.props.navigator}/>
                                )
                            }}
                            renderStickyHeader={()=> _renderStickyHeader(this.state.introduce.title)}
                        >
                            <TouchableOpacity
                                onPress={()=> {
                                    this.props.navigator.push({
                                        name: 'AllCommentPage',
                                        component: AllCommentPage,
                                        passProps: {
                                            commentList: this.state.commentList,
                                            id:this.props.ID,
                                            type:3
                                        }
                                    })
                                }}
                                style={{
                                    padding: 15,
                                    borderBottomColor: '#F2F3F5',
                                    borderBottomWidth: 1,
                                }}
                            >
                                <View style={{
                                    flex: 1,
                                    flexDirection: 'row',
                                    alignItems: 'center',
                                }}>
                                    <View style={{flex: 1}}>
                                        <Text style={{fontSize: 12, color: '#666'}}>
                                            <Text style={{color: '#38D68B', fontSize: 14}}>
                                                {this.state.introduce.star + '.0 '}
                                            </Text>
                                            分
                                        </Text>
                                        {_renderStar(this.state.introduce.star, {marginTop: 5})}
                                    </View>
                                    <TouchableOpacity onPress={()=>{this.collect()}}>
                                        <Image style={{marginRight:10,width:18,height:18,resizeMode:'contain'}}
                                               source={collectImg}
                                        />
                                    </TouchableOpacity>
                                    <Text style={{fontSize: 14, color: '#666'}}>全部评论</Text>
                                    <Image source={require('../../Image/arrow.png')}
                                           style={{
                                               resizeMode: 'contain',
                                               width: 20,
                                               height: 20,
                                               marginLeft: 5,
                                               marginRight: 3
                                           }}/>
                                </View>
                            </TouchableOpacity>
                            <WebContainer html={html} />
                            <WatchMapView {...this.state.introduce} isNotShowPrice={true}
                                                                    navigator={this.props.navigator} type={1}/>
                            {this._renderRoomView()}
                            {this.state.hotelList!='' ? <View style={styles.borderStyles}>
                                <View style={styles.somethingStyle}>
                                    <Image style={{width: 15,height: 15,marginRight: 10,resizeMode: 'contain'}}
                                           source={require('../../Image/icon_gray_live.png')}
                                    />
                                    <Text style={{color: '#333', fontSize: 16}}>住哪里</Text>
                                </View>
                                <View style={{padding: 10, flexDirection: 'row'}}>
                                    {
                                        this.state.hotelList ?
                                            this.state.hotelList.map((item, index) => {
                                                return (
                                                    <SomethingItemView
                                                        key={'near' + index}
                                                        item={item}
                                                        navigator={this.props.navigator}
                                                        component={StayDetailsPage}
                                                        name="StayDetailsPage"
                                                        textColor="red"
                                                    />
                                                )
                                            }) : null
                                    }
                                </View>
                            </View> : null}

                        </ParallaxScrollView>
                        :
                        <View style={{flex:1,backgroundColor:'#F5F5F5'}}>
                            <View
                            style={{position: 'absolute',top:0,left:0,width:Global.Const.size.width,height:Global.Const.size.height,backgroundColor:null,alignItems:'center',justifyContent:'center'}}>
                            <View
                                style={{backgroundColor:'#333333',borderRadius:5, alignItems: 'center',justifyContent: 'center',width:80,height:80}}>
                                <ActivityIndicator
                                    animating={this.state.animating}
                                    style={{ alignItems: 'center',justifyContent: 'center'}}
                                    size="large"/>
                                <Text style={{color:'white'}}>加载中...</Text>
                            </View>
                        </View>
                        </View>
                }
                <View style={[styles.content, {
                    width,
                    borderTopWidth: 1,
                    borderTopColor: "#F2F3F5"
                }]}>
                    <View
                        style={[styles.content, {
                            flex: 1,
                            borderRightWidth: 1,
                            borderRightColor: '#F2F3F5',
                        }]}
                    >
                        <Text style={styles.textBox}><Text style={{fontSize: 16}}>￥ {this.state.introduce.price?this.state.introduce.price:0}</Text></Text>
                    </View>
                    <TouchableOpacity
                        style={[styles.content, {
                            flex: 1,
                        }]}
                        onPress={() => {
                           this.ReviewsContainer(this.props.ID,3);
                         }}>
                        <View
                            style={[styles.content, {
                            flex: 1,
                            borderRightWidth: 1,
                            borderRightColor: '#F2F3F5',
                        }]}
                        >
                            <Image style={{  width: 15,height: 15,resizeMode: 'contain',marginRight: 8,}}
                                   source={require('../../Image/icon_comment.png')}/>
                            <Text style={{  fontSize: 15,color: '#38D68B'}}>点评</Text>
                        </View>
                    </TouchableOpacity>
                    <TouchableOpacity
                        onPress={() => {
                            if (Platform.OS === 'android') {
                                NativeModules.MakePhoneCallModule.makePhoneCall(this.state.introduce.phone);
                            }

                            if (Platform.OS === 'ios') {
                                //这个方法应该是Android/iOS通用的
                                Linking.openURL('tel:' + "07562287058").catch(err => console.log('打开电话失败:', err));

                            }
                        }}
                        style={[styles.content, {
                            flex: 2,
                            backgroundColor: "#38D68B"
                        }]}
                    >
                        <Text style={[styles.textBox, {fontSize: 16, color: "white"}]}>我要预订</Text>
                    </TouchableOpacity>
                </View>

                <BottomShareView
                    shareTitle={ this.state.introduce.title}
                    shareContent={this.state.introduce.desc}
                    shareImageUrl={this.state.images[0]}
                    shareUrl={'http://xc.xiarikui.cn/Api/Index/share'}
                    ref={(ref) => {this.shareView = ref;}}/>
            </View>

        )
    }
}

export default StayDetailsPage;